import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import session from 'koa-session';
import mongoose from 'mongoose';
import { config, validateConfig } from './config';
import { database } from './config/database';
import { applyMiddleware } from './middleware';
import authRouter from './routes/auth';

/**
 * 企业级用户中心服务
 * 基于Koa + TypeScript + MongoDB的四层架构设计
 */
class UserCenterService {
  private app: Koa;
  private server: any;

  constructor() {
    this.app = new Koa();
  }

  /**
   * 初始化应用
   */
  public async init(): Promise<void> {
    try {
      // 验证配置
      validateConfig();

      // 连接数据库
      await database.connect();

      // 设置中间件
      this.setupMiddleware();

      // 设置路由
      this.setupRoutes();

      // 设置错误处理
      this.setupErrorHandling();

      console.log('✅ User Center Service initialized successfully');
    } catch (error) {
      console.error('❌ Failed to initialize User Center Service:', error);
      throw error;
    }
  }

  /**
   * 设置中间件
   */
  private setupMiddleware(): void {
    // 应用基础中间件（错误处理、日志、CORS）
    applyMiddleware(this.app);

    // Body解析中间件
    this.app.use(
      bodyParser({
        enableTypes: ['json', 'form'],
        jsonLimit: '10mb',
        formLimit: '10mb',
      })
    );

    // Session中间件
    this.app.keys = [config.session.secret];
    this.app.use(
      session(
        {
          key: config.session.key,
          maxAge: config.session.maxAge,
        },
        this.app
      )
    );
  }

  /**
   * 设置路由
   */
  private setupRoutes(): void {
    // 健康检查路由
    this.app.use(async (ctx, next) => {
      if (ctx.path === '/health') {
        ctx.status = 200;
        ctx.type = 'application/json';

        // 直接检查mongoose连接状态，兼容测试环境
        const isDbConnected = mongoose.connection.readyState === 1;

        ctx.body = {
          success: true,
          message: 'User Center Service is running',
          timestamp: new Date().toISOString(),
          version: '1.0.0',
          database: isDbConnected ? 'connected' : 'disconnected',
        };
        return;
      }
      await next();
    });

    // API路由
    // 认证路由
    this.app.use(authRouter.routes()).use(authRouter.allowedMethods());
    
    // TODO: 添加用户管理路由
    // TODO: 添加组织架构路由
    // TODO: 添加权限管理路由

    // 404处理
    this.app.use(async ctx => {
      ctx.status = 404;
      ctx.type = 'application/json';
      ctx.body = {
        success: false,
        message: 'Route not found',
        path: ctx.path,
      };
    });
  }

  /**
   * 设置错误处理
   */
  private setupErrorHandling(): void {
    // 全局错误处理
    this.app.on('error', (error, ctx) => {
      console.error('Application error:', error);
    });

    // 未捕获异常处理
    process.on('uncaughtException', error => {
      console.error('Uncaught Exception:', error);
      process.exit(1);
    });

    // 未处理的Promise拒绝
    process.on('unhandledRejection', (reason, promise) => {
      console.error('Unhandled Rejection at:', promise, 'reason:', reason);
      process.exit(1);
    });
  }

  /**
   * 启动服务
   */
  public async start(): Promise<void> {
    try {
      // 初始化应用（包括数据库连接）
      await this.init();

      // 启动HTTP服务器
      this.server = this.app.listen(config.port, () => {
        console.log(`🚀 User Center Service is running on port ${config.port}`);
        console.log(`📊 Environment: ${config.nodeEnv}`);
        console.log(`🗄️  Database: ${config.database.name}`);
      });
    } catch (error) {
      console.error('❌ Failed to start User Center Service:', error);
      throw error;
    }
  }

  /**
   * 获取Koa应用实例（用于测试）
   */
  public getApp(): Koa {
    return this.app;
  }

  /**
   * 停止服务
   */
  public async stop(): Promise<void> {
    try {
      if (this.server) {
        this.server.close();
        console.log('✅ HTTP server stopped');
      }

      await database.disconnect();
      console.log('✅ User Center Service stopped');
    } catch (error) {
      console.error('❌ Error stopping User Center Service:', error);
      throw error;
    }
  }
}

// 创建并导出服务实例
const userCenterService = new UserCenterService();

// 如果直接运行此文件，则启动服务
if (require.main === module) {
  userCenterService.start().catch((error: any) => {
    console.error('Failed to start service:', error);
    process.exit(1);
  });
}

// 默认导出实例
export default userCenterService;
export { userCenterService as UserCenterService };
